package com.zyg.tools;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3p0Util {
	//利用ComboPooledDataSource获取一个数据库连接池对象，它会自动加载配置的xml文件
	static ComboPooledDataSource source = new ComboPooledDataSource();
	/*
	 * static { try { //设置数据库连接池中的参数信息，这样直接设置属于硬编码，不推荐，推荐在xml中设置这些参数
	 * source.setDriverClass("com.mysql.jdbc.Driver"); source.setUser("root");
	 * source.setPassword("asd123");
	 * source.setJdbcUrl("jdbc:mysql://localhost:3306/spring");
	 * source.setInitialPoolSize(10);
	 * 
	 * } catch (PropertyVetoException e) { e.printStackTrace(); }
	 * 
	 * }
	 */
	//配置xml文件后，直接返回connection对象
	public static Connection getConnection() {
		
		try {
			return source.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException("服务器忙。。。。。");
		}
	}
	//释放资源重新放回连接池
	public static void release(Connection conn,PreparedStatement ps,ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
